#!/usr/bin/perl

$SEP=(`uname -a` =~ /CYGWIN/ ? ";" : ":");

$teamA=$ARGV[0];
$teamAclass=$ARGV[1];
$teamB=$ARGV[2];
$teamBclass=$ARGV[3];
$numgames=$ARGV[4];
$timeout=$ARGV[5];
$gametype=$ARGV[6];

$teamAscore = 0;
$teamBscore = 0;

for($i=0; $i<$numgames; $i++) {
	$order = $i % 2;	

	system("killall -9 java");

	open(SERVER, "java -cp \"lib/java-getopt-1.0.13.jar${SEP}build\" assg.funnycells.server.Coordinator -l0 -x $timeout -v1 -t \"$teamA $teamAscore : $teamB $teamBscore\" -r $teamA -g $teamB | grep \"EXITSTATUS\" & |"); 

	sleep(2);

	if($gametype =~ /cluster/) {
		system("perl funnygamecluster.pl $teamAclass $teamBclass $order > /dev/null");
	} else {
		system("perl funnygamerandom.pl $teamAclass $teamBclass $order > /dev/null");
	}

	while(<SERVER>) {
		chomp;
		($dummy, $numsusceptible, $numA, $numB) = split(/#/);
	}

	close(SERVER);

	if($numsusceptible <= 5 && $numA - $numB >= 10 || $numB < 2) {
		$teamAscore += 2;
		print "       $teamA wins! This game: $numsusceptible $numA $numB\n";
		print "              Score so far: $teamAscore - $teamBscore\n";
	} elsif($numsusceptible <= 5 && $numB - $numA >= 10 || $numA < 2) {
		$teamBscore += 2;
		print "       $teamB wins! This game: $numsusceptible $numA $numB\n";
		print "              Score so far: $teamAscore - $teamBscore\n";
	} else {
		$teamAscore ++;
		$teamBscore ++;
		print "       Draw! This game: $numsusceptible $numA $numB\n";
		print "              Score so far: $teamAscore - $teamBscore\n";
	}  

	system("sleep 2");
}

if($teamAscore > $teamBscore) {
	print "       RESULT_WIN:$teamA\n";	
} elsif($teamBscore > $teamAscore) {
	print "       RESULT_WIN:$teamB\n";
} else {
	print "       RESULT_DRAW\n";
}



